<?php
	include_once('dbcon.php');
	include_once('constants.php');
	include_once('error_log_db.php');
	include_once('update_user_points_db.php');
	include_once('general_functions_db.php');

	function checkValidEditContent($content_id, $user_id) {
		global $mysqli;

		$content_query = $mysqli->query("SELECT content, user_id, creation_date FROM contents WHERE content_id=".$content_id);
		logIfError($mysqli, $_REQUEST['user_id'], "upload_category_db", "checkValidEditContent", "1");
		$content = $content_query->fetch_assoc();

		if (time() - strtotime($content['creation_date']) > CONTENT_MAX_EDIT_TIME + SERVER_SIDE_EXTRA_WAIT_TIME) {
			logMsg($user_id, "EDIT CONTENT INVALID. content_id=".$content_id.". content=".$content['content']);
			return false;
		}

		if ($content['user_id'] != $user_id) {
			logMsg($user_id, "EDIT CONTENT INVALID USER. content_id=".$content_id.". Owner_user=".$content['user_id']." Fake_user=".$user_id);
			return;
		}

		return true;
	}

	if(isset($_REQUEST['user_id']) && isset($_REQUEST['content']) && isset($_REQUEST['first_name']) && isset($_REQUEST['last_name'])) {

		$user_id = adaptToSql($_REQUEST['user_id']);
		$content = adaptToSql($_REQUEST['content']);
		$first_name = adaptToSql($_REQUEST['first_name']);
		$last_name = adaptToSql($_REQUEST['last_name']);

		$isAnonymous = $_REQUEST['is_anonymous'] == "true" ? "1" : "0";
		if (isset($_REQUEST['content_id'])) {
			if (checkValidEditContent($_REQUEST['content_id'], $user_id) == false) {
				echo $_REQUEST['content_id'];
				return;
			}
			
			$mysqli->query("UPDATE contents SET content=\"".$content."\", isAnonymous=\"".$isAnonymous."\" WHERE content_id=".$_REQUEST['content_id']);
		} else {
			$mysqli->query("INSERT INTO contents (user_id, first_name, last_name, content, likes, dislikes, points, isBest, isAnonymous, category_id, creation_date) VALUES('".$user_id."',\"".$first_name."\",\"".$last_name."\",\"".$content."\",'0','0','0','0','".$isAnonymous."','".$_REQUEST['category_id']."','".date('Y-m-d H:i:s')."')");
		}

		logIfError($mysqli, $user_id, "upload_content_db", "", "1");
		
		updateUserPoints($user_id);

		$action = null;
		$content_id = null;
		if (isset($_REQUEST['content_id'])) {
			$action = "Content edited.";
			$content_id = $_REQUEST['content_id'];
		} else {
			$action = "Content created.";
			// Get the last posted content by the user
			$content_query = $mysqli->query("SELECT * FROM contents WHERE user_id=".$user_id." ORDER BY content_id DESC LIMIT 1");
			logIfError($mysqli, $user_id, "upload_content_db", "", "2");
			
			$content_db = $content_query->fetch_assoc();
			
			$content_id = $content_db['content_id'];
		}

		logMsg($user_id, $action." ContentId=".$content_id.". Content=".$content);
		echo $content_id;
	}
?>
